package carshow;


import org.quickserver.net.*;
import org.quickserver.net.server.*;
import java.io.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * An implementation of the QuickServer application for use in the CarShow
 * application.  This is a port/customization of the QuickServer.  This
 * implements a singleton factory pattern so only one SQLiteQS is ever allowed
 * to run on the system.  This protects against multiple copies of the client
 * CarShowUI application running multiple servers.
 * @author wmotycka
 */
public class SQLiteQS extends Thread {

    private static QuickServer realQSDB = null;
    private static SQLiteQS realShowDB = null;

    private volatile Thread listen;
    /** The SQLiteDB IP port */
    public static final int PORT = 8454;
    /** public access method to get the current active SQLiteQS server instance */
    public static SQLiteQS getSQLiteQS() {
        if (SQLiteQS.realShowDB == null)
            SQLiteQS.realShowDB = new SQLiteQS();
        return SQLiteQS.realShowDB;
    }
    /* protected constructor ensures singleton pattern */
    private SQLiteQS() {
        //listen = this;
        SQLiteQS.realQSDB = new QuickServer("carshow.SQLiteCommandHandler");
	SQLiteQS.realQSDB.setPort(PORT);
        SQLiteQS.realQSDB.setTimeout(21600000); // 6 hour conn limit
	//SQLiteQS.realQSDB.setClientAuthenticationHandler("carshow.SQLiteQSAuthenticator");
        SQLiteQS.realQSDB.setName("SQLite-QS v 0.1");

        // add here the logging aspects of QuickServer
    }

    /**
     * starts the QuickServer SQLite DB access service.
     */
    @Override
    public void run() {
        try {
            realQSDB.startServer();
        } catch (AppException e) {
            String msg = e.getLocalizedMessage();
            if(!msg.contains("Address already in use")) {
                Logger.getLogger(CarShowUI.class.getName()).log(Level.SEVERE,
                    "Error in server : "+e);
                //e.printStackTrace(System.err);
            }
            else {
                Logger.getLogger(CarShowUI.class.getName()).log(Level.INFO, 
                    "SQLiteQS: Server running in another instance of CarShow"+
                    "on this system.");
            }
        }
    }
    /**
     * halts the running (local) QuickServer and SQLiteQS thread.
     */
    public void halt() {
        Thread tmpListen = listen;
        listen = null;
        if (tmpListen != null) {
            try {
                realQSDB.stopServer();
            }
            catch (AppException ae) {
                Logger.getLogger(CarShowUI.class.getName()).log(Level.SEVERE,
                    "Error on server stop: "+ae.toString(),ae);
                //ae.printStackTrace(System.err);
            }
            tmpListen.interrupt();
        }
        System.exit(0);
    }
}